package com.ofek.applicationbase.forms;

import java.util.ArrayList;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.Toast;

import com.ofek.applicationbase.R;

/**
 * call initForm() on the end of onCreate()
 * @author Ofek
 *
 */
public abstract class FormActivity extends ListActivity {
	
	protected ArrayList<QuestionViewController> questions;
	private QuestionAdapter qAdapter;
	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	protected void initForm(final boolean submitable)  {
		questions = createQuestions();

		getListView().invalidateViews();
		qAdapter = new QuestionAdapter(FormActivity.this, questions);
		qAdapter.setSubmitable(submitable);
		setListAdapter(qAdapter);
	}
	protected void initForm()  {
		initForm(true);
	}
	protected void initForm(final int submitRes)  {
		initForm();
		qAdapter.setSubmitResource(submitRes);
	}
	public abstract void onFormSubmitted();
	protected abstract ArrayList<QuestionViewController> createQuestions();




	public void notifyFormHasChanged() {
		qAdapter.notifyDataSetInvalidated();
	}


	
	public void onSubmit() {
		boolean valid = true;
		for (final QuestionViewController item : questions) 
			valid &= item.onSubmitRequested(true);
		if ( valid ) 
			onFormSubmitted();
		else 
			Toast.makeText(FormActivity.this, R.string.form_error_fields_missing, Toast.LENGTH_LONG).show();
	}
	
	
}
